package com.nononsenseapps.feeder.ui.qr

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.hmsscankit.WriterException
import com.huawei.hms.ml.scan.HmsBuildBitmapOption
import com.huawei.hms.ml.scan.HmsScan
import com.nononsenseapps.feeder.db.ARG
import com.nononsenseapps.feeder.ui.R
import com.nononsenseapps.feeder.ui.base.CoroutineScopedActivity
import com.nononsenseapps.feeder.util.naiveFindUrlLink
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class GenerateQRCodeActivity : CoroutineScopedActivity() {

    private lateinit var barcodeTitle: TextView
    private lateinit var barcodeImage:ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        if (shouldBeFloatingWindow()) {
            setupFloatingWindow()
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_generate_qr_code)

        // Not persisted so set nightmode every time we start
        AppCompatDelegate.setDefaultNightMode(settingsViewModel.themePreference)

        barcodeTitle = findViewById(R.id.barcode_title)
        barcodeImage = findViewById(R.id.barcode_image)

        intent?.let { intent ->
            if(intent.getStringExtra(ARG.LINK)==null) {//share
                val shardStr = (intent.dataString ?: intent.getStringExtra(Intent.EXTRA_TEXT)
                ?: "").trim()
                // Link
                val urlLink = naiveFindUrlLink(shardStr) ?: shardStr
                barcodeTitle.text = urlLink
                generateQRCode(urlLink)
            }else{
                //url
                intent.getStringExtra(ARG.LINK)?.let {
                    barcodeTitle.text = it
                    generateQRCode(it)
                }
                // Title
                intent.getStringExtra(ARG.TITLE)?.let {
                    barcodeTitle.text = it
                }
            }
        }
    }

    fun generateQRCode(content:String){
        lifecycleScope.launch {
            try {
                //Generate the barcode.
                val options = HmsBuildBitmapOption.Creator().setBitmapColor(Color.BLACK).create()
                val resultImage = ScanUtil.buildBitmap(content, HmsScan.QRCODE_SCAN_TYPE, 500, 500, options)
                withContext(Dispatchers.Main) {
                    barcodeImage.setImageBitmap(resultImage)
                }
            } catch (e: WriterException) {
                Toast.makeText(baseContext, "Parameter Error!", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun getFloatingWindowHeight(): Int {
        return 900
    }
}